<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模版名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入模版编码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模版状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="模版状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_tenant_package_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱账号" prop="accountId">
        <el-select
          v-model="queryParams.accountId"
          placeholder="邮箱账号"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in accountList"
            :key="dict.id"
            :label="dict.mail"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:mail:template:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList">
      <el-table-column label="模版编码" prop="code" width="120" />
      <el-table-column label="模版名称" prop="name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="模板标题" prop="title" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="模板内容" prop="content" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="发送人" prop="nickname" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="邮箱账号" prop="account" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="状态" prop="status" :show-overflow-tooltip="true" width="150">
        <template v-slot="scope">
          <dict-tag :options="dict.type.sys_tenant_package_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-share" @click="handleSend(scope.row)"
                     v-hasPermi="['system:mail:template:send-mail']">测试</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:mail:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:mail:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item prop="name" label="名称">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入模板编号" />
        </el-form-item>
        <el-form-item label="邮箱账号" prop="accountId">
          <el-select
            v-model="form.accountId"
            placeholder="邮箱账号"
            clearable
          >
            <el-option
              v-for="dict in accountList"
              :key="dict.id"
              :label="dict.mail"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="nickname" label="发送人名称">
          <el-input v-model="form.nickname" placeholder="请输入发送人名称" />
        </el-form-item>
        <el-form-item prop="title" label="模版标题">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item prop="content" label="模版内容">
          <editor v-model="form.content" :min-height="192" readonly />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_tenant_package_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="form.remark" placeholder="请输入发送人名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(发送邮件) -->
    <el-dialog title="测试发送邮件" :visible.sync="sendOpen" width="500px" append-to-body>
      <el-form ref="sendForm" :model="sendForm" :rules="sendRules" label-width="140px">
        <el-form-item label="模板内容" prop="content">
          <editor v-model="sendForm.content" :min-height="192" readonly />
        </el-form-item>
        <el-form-item label="收件邮箱" prop="mail">
          <el-input v-model="sendForm.mail" placeholder="请输入收件邮箱" />
        </el-form-item>
        <el-form-item v-for="param in sendForm.params" :key="param" :label="'参数 {' + param + '}'" :prop="'templateParams.' + param">
          <el-input v-model="sendForm.templateParams[param]" :placeholder="'请输入 ' + param + ' 参数'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSendForm">确 定</el-button>
        <el-button @click="cancelSend">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { create,update,deleteTemplate,getDetail,page,send } from "@/api/system/mailTemplate"
import { accountList } from "@/api/system/mailAccount"
import Editor from '@/components/Editor'
export default {
  name: 'mailTemplate',
  components: {
    Editor,
  },
  dicts: ['sys_tenant_package_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      templateList: [],
      accountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        accountId: null,
        status: null
      },
      //租户初始化账号信息
      account:{},
      //是否显示账号信息弹框
      openAccount: false,
      //是否展示测试发送对话框
      sendOpen: false,
      // 表单参数
      form: {},
      //发送短信参数
      sendForm: {
        params: [], // 模板的参数列表
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "模版编号不能为空,唯一", trigger: "blur" }
        ],
        accountId: [
          { required: true, message: "发送的邮箱账号编号不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }]
      },
      sendRules: {
        mail: [{ required: true, message: "收件邮箱不能为空", trigger: "blur" }],
        templateCode: [{ required: true, message: "模版编码不能为空", trigger: "blur" }],
        templateParams: { }
      }
    };
  },
  created() {
    this.getList();
    this.getAccountList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      page(this.queryParams).then(response => {
          this.templateList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    getAccountList() {
      accountList().then(res=>{
        this.accountList=res.data
      })
    },
    /** 搜索按钮 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(){
      this.reset();
      this.open = true;
      this.title = "添加邮件模板";
    },
    /** 修改按钮 */
    handleUpdate(row) {
      this.reset();
      getDetail(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改邮件模版";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            create(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮 */
    handleDelete(row){
      this.$modal.confirm('是否确认删除邮件模版编号为"' + row.code + '"的数据项？').then(function() {
        return deleteTemplate(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        id: undefined,
        name: undefined,
        code: undefined,
        accountId: undefined,
        nickname: undefined,
        title:undefined,
        content:undefined,
        status:undefined,
        remark:undefined
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //测试发送
    handleSend(row) {
      this.resetSend(row);
      // 设置参数
      this.sendForm.content = row.content;
      this.sendForm.params = row.params;
      this.sendForm.templateCode = row.code;
      debugger
      if (row.params!=undefined||row.params != null){
        this.sendForm.templateParams = row.params.reduce(function(obj, item) {
          obj[item] = undefined;
          return obj;
        }, {});
        // 根据 row 重置 rules
        this.sendRules.templateParams = row.params.reduce(function(obj, item) {
          obj[item] = { required: true, message: '参数 ' + item + " 不能为空", trigger: "change" };
          return obj;
        }, {});
      }
      // 设置打开
      this.sendOpen = true;
    },
    /** 重置发送邮箱的表单 */
    resetSend() {
      // 根据 row 重置表单
      this.sendForm = {
        content: undefined,
        params: undefined,
        mail: undefined,
        templateCode: undefined,
        templateParams: {}
      };
      this.resetForm("sendForm");
    },
    /** 提交发送*/
    submitSendForm(){
      this.$refs["sendForm"].validate(valid => {
        if (!valid) {
          return;
        }
        // 添加的提交
        send(this.sendForm).then(response => {
          this.$modal.msgSuccess("提交发送成功！发送结果，见发送日志编号：" + response.data);
          this.sendOpen = false;
        });
      });
    },
    /** 取消发送*/
    cancelSend(){
      this.sendOpen = false;
      this.resetSend();
    }
  }
}
</script>
